package com.woniuxy.three.pms.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.woniuxy.three.pms.bean.RootBean;
import com.woniuxy.three.pms.root.service.IRootService;

/**
 * 
 * @ProjectName: RoomManagerSystem
 * @Package: com.woniuxy.three.pms.shiro
 * @ClassName: 
 * @author 郑杰  
 * @Description:自定义realm
 * @date 2019年6月24日  下午7:35:06
 * @Version:1.0
 * @See：1.0
 */
public class RootRealm extends AuthorizingRealm{
	@Autowired
	private IRootService service;
	//执行授权逻辑
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("执行授权逻辑");
		
		  SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		  Subject subject = SecurityUtils.getSubject();
		  RootBean root = (RootBean)subject.getPrincipal();
		  info.addStringPermission(root.getRoleBean().getRole());
		 
		return info;
	}
	//执行认证逻辑
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("执行认证逻辑");
		UsernamePasswordToken token2 = (UsernamePasswordToken) token;
		RootBean root = service.login(token2.getUsername());
		if (root==null) {
			return null;
		}
		ByteSource nameSalt = ByteSource.Util.bytes(token2.getUsername());
		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(root,root.getPassword(),nameSalt,getName());
		return info;
	}
	
	public static void main(String[] args) {
		ByteSource byteSource = ByteSource.Util.bytes("zhengjie");
		Object simpleHash = new SimpleHash("MD5","987654",byteSource,1024);
		System.out.println(simpleHash.toString());
	}

}

